<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- BIM成果列表 -->
    <div id="base-breadcrumb" style="position: relative; overflow: hidden">
      <!-- 搜索 -->
      <searchData :search-data="searchArr" @search="search" />
      <!-- 表格 -->
      <a-card :bordered="false">
        <!-- <title-name :title="$route.meta.title" /> -->
        <!-- 表格 -->
        <list-table
          ref="table"
          :page-keys="['pageNum', 'pageSize', 'total']"
          :columns="columns"
          :request="loadData"
          :start-index="0"
          :filter-data="filterData"
          :statistics-config="{
            use: true, //是否统计，传false不会显示操作栏
            temp: statistics
          }"
          :export-permission="{ select: 'BIM_002_exp_05', all: 'BIM_002_exp_05' }"
          :export-config="{ use: true, select: $route.meta.title, all: $route.meta.title }"
        >
          <!-- 新增 -->
          <a-button
            slot="prefix"
            v-btnPermission="'BIM_002_add_01'"
            class="mb12"
            icon="plus"
            type="primary"
            @click="handleManage(2)"
          >
            新增
          </a-button>
          <!-- 下载附件 -->
          <template slot="suffix" slot-scope="scoped">
            <a-button
              v-btnPermission="'BIM_002_dow_06'"
              :loading="downLoading"
              class="mb12"
              icon="cloud-download"
              :disabled="scoped.selectedRowKeys && scoped.selectedRowKeys.length === 0"
              type="primary"
              @click="downZip(scoped.selectedRowsMap)"
            >
              批量下载附件
            </a-button>
            <ExportExcel
              ref="exportExcel"
              :export-list="exportList"
              :loading="loadingExport"
              icon="export"
              :file-name="$route.meta.title + '模板.xlsx'"
              button-text="下载导入模板"
              :beforeDownload="beforeDownload"
            />
            <ExcelImportButton
              ref="excelImportButton"
              :loading="loadingImport"
              icon="import"
              button-text="批量导入"
              v-if="hideBuquBtn()"
              @handleSubmit="handleImport"
            />
          </template>
          <template slot="actions" slot-scope="text, record">
            <MoreButton>
              <!-- <a v-btnPermission="'BIM_002_loo_02'" @click="handleManage(0, record)">查看</a> -->
              <template v-if="record.fileInfoList && record.fileInfoList.length > 0">
                <a
                  v-btnPermission="'BIM_002_ann_07'"
                  @click="
                    fileList = record.fileInfoList
                    visible = true
                  "
                  >查看附件({{ record.fileInfoList ? record.fileInfoList.length : 0 }})</a
                >
                <a-divider v-btnPermission="'BIM_002_ann_07'" type="vertical" />
              </template>
              <a v-btnPermission="'BIM_002_edi_03'" @click="handleManage(1, record)">编辑</a>
              <template>
                <a-divider v-btnPermission="'BIM_002_del_04'" type="vertical" />
                <a v-btnPermission="'BIM_002_del_04'" class="del_btn" @click="handleRemove(record.id, search)">删除</a>
              </template>
            </MoreButton>
          </template>
        </list-table>
      </a-card>
    </div>
    <!-- 查看附件 -->
    <DialogForm ref="dialogForm" :visible.sync="visible" edit-model="V" :width="1000" :fileList="fileList" />
    <ExportResult :visible.sync="visibleExport" :exportList="exportList" />
  </base-breadcrumb>
</template>

<script>
import { getPageTypesLabel } from '@/api/bimIntegrate/bimResource.js'
import {
  getPageBimResult,
  deleteBimResult,
  bimResultSummary,
  insertBimResultBatch
} from '@/api/bimIntegrate/bimResult.js'
import BasePage from '@/views/basePage'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import DialogForm from '@/components/DialogForm' // 弹窗
import ExportResult from '@/components/Dialog/ExportResult' // 弹窗
import Selector from '@/components/Select/Selector'
import ExportExcel from '@/components/exportExcel/ExportExcel' // 导出
import OrgTreeSelect from "@/components/OrgTreeSelect"

const searchArr = [
  // 搜索框
  {
    name: '成果所有者',
    valueKey: 'searchQuery',
    type: OrgTreeSelect
  },
  {
    name: '类型',
    valueKey: 'type',
    type: Selector,
    customApi: getPageTypesLabel,
    customQuery: { param: { type: '31' } },
    dataValue: 'data.list'
  },
  {
    name: '成果名称',
    type: 'input',
    value: 'resultName'
  },
  {
    name: '成果评价',
    type: 'select',
    value: 'resultLevel',
    data: [
      {
        label: '优秀',
        value: 0
      },
      {
        label: '一般',
        value: 1
      },
      {
        label: '差',
        value: 2
      }
    ]
  },
  {
    name: '完成日期',
    type: 'dateRange',
    value: 'trainTime',
    attr: {
      rangeFormat: ['startTime', 'endTime']
    }
  }
]
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 80,
    isHidden: true,
    customRender() {
      return Number(arguments[2]) + 1
    }
  },
  {
    title: '成果所有者',
    ellipsis: true,
    dataIndex: 'unitName'
  },
  {
    title: '成果名称',
    ellipsis: true,
    dataIndex: 'resultName'
  },
  {
    title: '类型',
    ellipsis: true,
    dataIndex: 'typeName',
    excelConfig: {
      dataValidation: {
        type: 'list'
      }
    }
  },
  {
    title: '成果制作人',
    ellipsis: true,
    dataIndex: 'resultProducer',
    excelConfig: {
      note: '多条采用小写逗号分隔，如：张三,李四'
    }
  },
  {
    title: '完成日期',
    ellipsis: true,
    dataIndex: 'finishDate',
    excelConfig: {
      note: '日期格式：XXXX年XX月XX日；如：2020年5月1号'
    }
  },
  {
    title: '成果评价',
    ellipsis: true,
    isHidden: true,
    dataIndex: 'resultLevel',
    customRender() {
      return ['优秀', '一般', '差'][arguments[0]] || '无'
    }
  },
  {
    title: '备注',
    ellipsis: true,
    dataIndex: 'remark'
  },
  {
    title: '更新时间',
    width: 160,
    isHidden: true,
    ellipsis: true,
    dataIndex: 'modifiedTime'
  },
  {
    title: '操作',
    dataIndex: 'actions',
    isHidden: true,
    width: '230px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'actions' }
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BasePage(),
  components: {
    DialogForm,
    ExportResult,
    ExportExcel
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      queryParam: {}, // 查询参数
      visible: false, // 查看附件弹窗控件
      visibleExport: false, // 导入结果弹窗控件
      exportList: [{ columns: [], datas: [] }], // 导入配置项
      fileList: [], // 当前文件列表
      loadingImport: false, // 导入loading
      loadingExport: false, // 导出loading
      removeApi: { remove: deleteBimResult }, // 删除台账
      countInfo: {}, // 汇总数据
      countList: [
        {
          title: '公司：',
          value: 'company'
        },
        {
          title: '分公司：',
          value: 'branch'
        },
        {
          title: '项目：',
          value: 'project'
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        this.getSummary()
        const requestParameters = Object.assign({}, parameter, { param: this.queryParam })
        return getPageBimResult(requestParameters).then((res) => {
          if (res.code === '0') {
            return { code: 200, data: res.data?.list, total: res.data?.total }
          }
        })
      },
      importCheck: {
        成果名称: 'resultName',
        类型: 'typeName',
        成果所有者: 'unitName',
        成果制作人: 'resultProducer',
        完成日期: 'finishDate',
        备注: 'remark'
      } // 导入字段对应
    }
  },
  methods: {
    /**
     * @description: 导出模板前的回调处理
     * @param {Promise} callback：导出方法
     */
    async beforeDownload() {
      let columnsExport = this.$clone(this.columns)
      // 若类别枚举值不存在，则添加类别的枚举值
      if (!columnsExport[3].options || columnsExport[3].options.length === 0) {
        this.loadingExport = true
        const res = await getPageTypesLabel({ param: { type: '31' } }).catch(() => {
          this.loadingExport = false
        })
        this.loadingExport = false
        if (res.code === '0') {
          columnsExport[3].options = res.data?.list?.map((item) => item.name)
        }
      }
      // 设置默认导出配置项
      this.exportList = [
        {
          columns: columnsExport,
          datas: [
            {
              resultName: '成果名称（必填）',
              unitName: '完成该成果的项目部',
              resultProducer: '完成该成果的人员（可添加多人）'
            }
          ]
        }
      ]
    },
    /**
     * @description: 批量导入
     * @param {Array} data：导入列表
     */
    handleImport(e) {
      let form = []
      for (let index in e) {
        form.push({})
        let keys = e[index]
        let listItem = form[index]
        // 校验excel的表头字段
        for (let i in this.importCheck) {
          let item = this.importCheck[i]
          if (!Object.keys(keys).includes(i) && item !== 'remark') {
            this.$message.warning(`第${Number(index) + 1}行${i}不能为空`)
            return
          } else {
            // 添加表单值，且格式化日期
            try {
              listItem[item] =
                item === 'finishDate' ? this.$dateFormat(keys[i].setDate(keys[i].getDate() - 1), 'D') : keys[i]
            } catch (error) {
              console.log(error)
              this.$message.warning(`第${Number(index) + 1}行${i}格式有误`)
              return
            }
          }
        }
      }
      this.loadingImport = true
      insertBimResultBatch(form)
        .then(async (res) => {
          this.loadingImport = false
          if (res.code === '0') {
            if (res.data?.list?.length > 0) {
              // 配置导出项，且打开导出结果
              let columnsExport = this.$clone(this.columns)?.filter((i) => i.header !== '操作' && !i.isHidden)
              if (!columnsExport[2].options || columnsExport[2].options.length === 0) {
                const ress = await getPageTypesLabel({ param: { type: '31' } }).catch(() => {
                  this.loadingImport = false
                })
                // 添加类别的下拉枚举值
                if (ress?.code === '0') {
                  columnsExport[2].options = ress.data?.list?.map((item) => item.name)
                }
              }
              // 表头添加失败原因
              columnsExport.push({
                dataIndex: 'failureReason',
                ellipsis: true,
                title: '失败原因'
              })

              this.exportList = [
                {
                  successCount: res.data.successCount,
                  columns: columnsExport,
                  datas: res.data.list
                }
              ]
              this.visibleExport = true
            } else {
              this.$message.success('导入成功')
            }
            // 如果有导入成功条数，则刷新表格
            res.data?.successCount > 0 && this.search()
          }
        })
        .catch(() => {
          this.loadingImport = false
        })
    },
    /**
     * @description: 格式话数据
     * @param {Array} datas：需要格式化的列表
     * @return {Array}
     */
    filterData(datas) {
      let list = this.$clone(datas)
      list.forEach((item, index) => {
        item.index = index + 1
        item.resultLevel = ['优秀', '一般', '差'][item.resultLevel]
      })
      return list
    },
    /**
     * 汇总请求
     */
    getSummary() {
      bimResultSummary({ param: this.queryParam }).then((res) => {
        if (res.code === '0') {
          this.countInfo = res.data
        }
      })
    },
    /**
     * 汇总
     */
    statistics() {
      return this.countList.map((item, index) => (
        <span key={index}>
          {item.title}
          <a>
            <b>{this.countInfo?.[item.value] || 0}</b>
          </a>
          个{index != this.countList.length - 1 ? '，' : ''}
        </span>
      ))
    },
    /**
     * @description: 搜索
     * @param {Object} value：搜索筛选对象
     */
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.getData(null, true)
    },
    /**
     * @description: 操作栏
     * @param {*} type：1：编辑；2：新增
     * @param {*} record：操作对象
     */
    handleManage(type, record) {
      this.editModel = type
      let query = {
        editModel: type
      }
      if (record && record.id) {
        query.id = record.id
      }
      this.$router.push({
        name: '/bimResult/achievementsEdit',
        query
      })
    }
  }
}
</script>
